import json
import logging
from pathlib import Path
from typing import Dict, Optional, Any
from src.config.settings import CACHE_DIR

class CacheManager:
    """缓存管理器"""
    
    def __init__(self, cache_dir: str = str(CACHE_DIR)):
        self.cache_dir = Path(cache_dir)
        self.cache_dir.mkdir(parents=True, exist_ok=True)
        self.logger = logging.getLogger(__name__)
        
    def get(self, key: str) -> Optional[Any]:
        """获取缓存"""
        try:
            cache_file = self.cache_dir / f"{key}.json"
            if cache_file.exists():
                with cache_file.open('r', encoding='utf-8') as f:
                    return json.load(f)
        except Exception as e:
            self.logger.error(f"读取缓存失败: {str(e)}")
        return None
        
    def set(self, key: str, value: Any) -> bool:
        """设置缓存"""
        try:
            cache_file = self.cache_dir / f"{key}.json"
            with cache_file.open('w', encoding='utf-8') as f:
                json.dump(value, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            self.logger.error(f"写入缓存失败: {str(e)}")
            return False
